//
//  KABCosReportVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/5/23.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABCosReportVC.h"
#import "KABCosReportTCell.h"
#import "KABCosReportEditTCell.h"
#import "SZTextView.h"
#import "MBProgressHUD+XDPrompt.h"
#import "GlobalHeader.h"
#import "KABModel.h"
#import "XDAFNetworking.h"
#import "ApiManager.h"

@interface KABCosReportVC ()<UITableViewDelegate, UITableViewDataSource, UITextViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UIView *tFooterBgView;
@property (weak, nonatomic) IBOutlet UIButton *tReportBtn;
@property (strong, nonatomic) NSArray<NSString *> *reportTitltArray;
@property (assign, nonatomic) NSInteger selIndex;
@property (copy,   nonatomic) NSString *inputStr;
@end

static NSString *const kReuseTCellId = @"KABCosReportTCell";
static NSString *const kReuseEditTCellId = @"KABCosReportEditTCell";

@implementation KABCosReportVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    self.navigationItem.title = @"举报原因";
}

- (void)initSubViews {
    self.tReportBtn.layer.masksToBounds = YES;
    self.tReportBtn.layer.cornerRadius = CGRectGetHeight(self.tReportBtn.bounds) / 2.0;
    [self.tReportBtn addTarget:self action:@selector(tReportBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    UINib *nib = [UINib nibWithNibName:kReuseTCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseTCellId];
    UINib *editNib = [UINib nibWithNibName:kReuseEditTCellId bundle:nil];
    [self.tableView registerNib:editNib forCellReuseIdentifier:kReuseEditTCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 65.0;
    self.tableView.tableFooterView = self.tFooterBgView;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    // 默认没有选择任何内容
    self.selIndex = -1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.reportTitltArray.count + (self.selIndex == self.reportTitltArray.count - 1 ? 1 : 0);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < self.reportTitltArray.count) {
        KABCosReportTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseTCellId forIndexPath:indexPath];
        cell.selBtn.selected = (indexPath.row == self.selIndex);
        cell.reportTitleLabel.text = self.reportTitltArray[indexPath.row];
        return cell;
    } else {
        KABCosReportEditTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseEditTCellId forIndexPath:indexPath];
        cell.reportTextView.text = self.inputStr;
        cell.reportTextView.delegate = self;
        return cell;
    }
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row < self.reportTitltArray.count) {
        self.selIndex = indexPath.row;
        [self refreshWholeView];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 8.0;
}

#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView {
    NSInteger maxLength = KABGlobalCosplayReportLength;
    NSString *toBeString = textView.text;
    //获取高亮部分
    UITextRange *selectedRange = [textView markedTextRange];
    UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position || !selectedRange) {
        if (toBeString.length > maxLength) {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:maxLength];
            if (rangeIndex.length == 1) {
                textView.text = [toBeString substringToIndex:maxLength];
            } else {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxLength)];
                textView.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
    
    self.inputStr = textView.text;
}

#pragma mark - event response
- (void)tReportBtnTapped:(UIButton *)btn {
    if (self.selIndex < 0) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"至少选择一项"];
        return;
    }
    
    if (self.selIndex == self.reportTitltArray.count - 1 && !self.inputStr.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请补充举报说明"];
        return;
    }
    
    NSString *reason = (self.selIndex < self.reportTitltArray.count - 1) ? self.reportTitltArray[self.selIndex] : self.inputStr;
    [self requestReportCosplay:reason];
}

#pragma mark - private methods
- (void)refreshWholeView {
    [self.tableView reloadData];
}

- (void)backToParent {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - network request
- (void)requestReportCosplay:(NSString *)reportReason {
    // 评论必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    if (!reportReason.length) {
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:@([KABModel sharedInstance].userInfo.uid) forKey:@"user_id"];
    [pars setObject:[KABModel sharedInstance].userInfo.access_token forKey:@"access_token"];
    [pars setObject:reportReason forKey:@"report_content"];
    if (self.cosplayId) {
        [pars setObject:@(self.cosplayId) forKey:@"cosplay_id"];
    }
    if (self.commentId) {
        [pars setObject:@(self.commentId) forKey:@"comment_id"];
    }
    
    NSString *apiStr = self.cosplayId ? [ApiManager apiCosplayReport] : [ApiManager apiCosCommentReport];
    [[XDAFNetworking sharedInstance] POST:apiStr parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [hud hideAnimated:YES];
        NSLog(@"举报返回：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            MBProgressHUD *hud = [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
            hud.completionBlock = ^{
                [self backToParent];
            };
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"举报失败：%@", error);
        [hud hideAnimated:YES];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters
- (NSArray<NSString *> *)reportTitltArray {
    if (!_reportTitltArray) {
        _reportTitltArray = @[@"广告等垃圾信息",
                              @"不宜公开讨论的政治问题",
                              @"不友善内容",
                              @"色情/血腥/暴力等违规内容",
                              @"盗用/抄袭他人作品",
                              @"其它"];
    }
    return _reportTitltArray;
}

@end
